package com.merge.sample;

import java.util.List;

import com.merge.sample.model.MProject;
import com.merge.sample.model.MResult;
import com.merge.sample.util.XMLPaser;

public class MergeHandler {

	public static String doMerge(String xmlPath, String targetPath, boolean useXmlPath) throws Exception {
		List<MResult> rl = XMLPaser.parseProj(xmlPath);
		if(rl.size()==0) {
			return "There is no data to deal with";
		}
		MProject project = rl.get(0).getProject();
		DefaultFolderMerge folderMerger = new DefaultFolderMerge(project.projectname);
		DefaultXMLFileMerge fileMerger = new DefaultXMLFileMerge(project.projectname);
		for(MResult r : rl) {
			String source = r.getFullPath();
			if(useXmlPath) {
				source = r.replaceBaseDir(xmlPath.substring(0, xmlPath.lastIndexOf("\\")));
			} 
			String target = r.replaceBaseDir(targetPath);
			if(r.isFile) {
				List<String> cl = fileMerger.checkConflict(source, target, r);
				if(cl==null || cl.size()>0) {
					return makeConflictMsg(cl, target);
				}
				String msg = fileMerger.doMerge(source, target, r);
				System.out.println(source + " " + msg);
			} else {
				List<String> cl = folderMerger.checkConflict(source, target, r);
				if(cl==null || cl.size()>0) {
					return makeConflictMsg(cl, target);
				}
				String msg = folderMerger.doMerge(source, target, r);
				System.out.println(msg);
			}
		}
		return CanMerge.SUCCESS;
	}
	
	private static String makeConflictMsg(List<String> cl, String target) {
		if(cl==null) {
			return "There is some error happened, cause cl is null";
		}
		StringBuilder sb = new StringBuilder();
		sb.append("Conflict: ")
			.append(target).append(" : [");
		for(String c : cl) {
			sb.append(c).append(", ");
		}
		sb.append("]");
		return sb.toString();
	}
	
	public static void main(String[] args) throws Exception {
		String xmlFile = "D:\\workspace_android\\Sample_Compie\\am_project.xml";
		String tfn = "D:\\workspace_android\\MergeTest2";
		String msg = MergeHandler.doMerge(xmlFile, tfn, true);
		System.out.println(msg);
	}
}
